package demo.android.ipc;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.hss01248.facedetect.activity.CollectActivity;
import com.hss01248.facedetect.utils.IDCardValidate;
import com.hss01248.facedetect.utils.ToastUtil;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.module.idcard.IDCardReader;
import com.zkteco.android.biometric.module.idcard.IDCardReaderFactory;
import com.zkteco.android.biometric.module.idcard.exception.IDCardReaderException;
import com.zkteco.android.biometric.module.idcard.meta.IDCardInfo;
import com.zkteco.android.biometric.module.idcard.meta.IDPRPCardInfo;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IllegalFormatCodePointException;
import java.util.Map;

import demo.android.ipc.custom_keyboard.CustomKeyboard;
import demo.android.ipc.custom_keyboard.MyKeyboardView;

public class SpecialCredentialsActivity extends AppCompatActivity implements View.OnClickListener {

    Handler handler_work = new Handler();


    EditText writebankcard_mobileedit;
    EditText writebankcard_Phone;
    CustomKeyboard mCustomKeyboard;
    CustomKeyboard mCustomKeyboardPhone;

    //    身份证模块
    private static final int VID = 1024;    //IDR VID
    private static final int PID = 50010;     //IDR PID


    private IDCardReader idCardReader = null;
    private TextView textView = null;
    private ImageView imageView = null;
    private boolean bopen = false;
    String idNumber = null;
    String idName = null;
    private RadioGroup rg;
    private Button btn1;
    private Button btn2;
    private Button btn3;
    private Button btn4;
    private Button btn5;
    private Button btn6;
    private Button btn7;
    private Button btn8;
    private Button btn9;
    private Button btn10;

    boolean isChose = false;
    Button[] buttonArray = new Button[2];
    String chooseValue;
    private Button btn_sure;

    ArrayList<Button> arrayList_button;
    private MyKeyboardView keyboardView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE); // 去掉标题栏 有效
        setContentView(R.layout.activity_special_credentials);

        writebankcard_mobileedit = (EditText) findViewById(R.id.writebankcard_mobileedit);
        writebankcard_Phone = (EditText) findViewById(R.id.writebankcard_mobileedit_phone);

        //1 屏蔽掉系统默认输入法
        if (Build.VERSION.SDK_INT <= 10) {
            writebankcard_mobileedit.setInputType(InputType.TYPE_NULL);
            writebankcard_Phone.setInputType(InputType.TYPE_NULL);
        } else {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(writebankcard_mobileedit, false);
                setShowSoftInputOnFocus.invoke(writebankcard_Phone, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //2 初试化键盘

        if (keyboardView == null) {
            keyboardView = (MyKeyboardView) findViewById(R.id.customKeyboard);
            mCustomKeyboardPhone = new CustomKeyboard(SpecialCredentialsActivity.this, keyboardView, writebankcard_Phone);
            mCustomKeyboardPhone.showKeyboard();
        }


        writebankcard_mobileedit.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mCustomKeyboard = new CustomKeyboard(SpecialCredentialsActivity.this, keyboardView, writebankcard_mobileedit);
                mCustomKeyboard.showKeyboard();
                return false;
            }
        });

        writebankcard_Phone.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mCustomKeyboardPhone = new CustomKeyboard(SpecialCredentialsActivity.this, keyboardView, writebankcard_Phone);
                mCustomKeyboardPhone.showKeyboard();
                return false;
            }
        });

        writebankcard_mobileedit.clearFocus();
        writebankcard_Phone.clearFocus();

        btn1 = (Button) findViewById(R.id.sa_btn1);
        btn2 = (Button) findViewById(R.id.sa_btn2);
        btn3 = (Button) findViewById(R.id.sa_btn3);
        btn4 = (Button) findViewById(R.id.sa_btn4);
        btn5 = (Button) findViewById(R.id.sa_btn5);
        btn6 = (Button) findViewById(R.id.sa_btn6);
        btn7 = (Button) findViewById(R.id.sa_btn7);
        btn8 = (Button) findViewById(R.id.sa_btn8);
        btn9 = (Button) findViewById(R.id.sa_btn9);
        btn10 = (Button) findViewById(R.id.sa_btn10);
//        arrayList_button = new ArrayList();
//        arrayList_button.add(btn1);
//        arrayList_button.add(btn2);
//        arrayList_button.add(btn3);
//        arrayList_button.add(btn4);
//        arrayList_button.add(btn5);
//        arrayList_button.add(btn6);
//        arrayList_button.add(btn7);
//        arrayList_button.add(btn8);
//        arrayList_button.add(btn9);

//        for (int i = 0; i < arrayList_button.size(); i++) {
//            arrayList_button.get(i).setBackgroundDrawable(new ColorDrawable(0xaa000000));
//        }


        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
        btn5.setOnClickListener(this);
        btn6.setOnClickListener(this);
        btn7.setOnClickListener(this);
        btn8.setOnClickListener(this);
        btn9.setOnClickListener(this);
        btn10.setOnClickListener(this);

        textView = (TextView) findViewById(R.id.textView);
        btn_sure = (Button) findViewById(R.id.sa_btn_sure);
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String idNumber = writebankcard_mobileedit.getText().toString().trim();
                String idPhome = writebankcard_Phone.getText().toString().trim();

                if (TextUtils.isEmpty(idNumber)) {
                    ToastUtil.showToast("请输入身份证号码");
                    return;
                } else if (!IDCardValidate.validate_effective(idNumber)) {
                    ToastUtil.showToast("身份证号码格式不正确，请重新输入");
                    return;
                }

                if (TextUtils.isEmpty(idPhome)) {
                    ToastUtil.showToast("请输入手机号码");
                    return;
                } else if (!IDCardValidate.isMobileNO(idPhome)) {
                    ToastUtil.showToast("请输入正确手机号码");
                    return;
                }
                if (chooseValue == "0") {
                    ToastUtil.showToast("请选择证件类型");
                    return;
                }

                Intent intent = new Intent(SpecialCredentialsActivity.this, CollectActivity.class);
                intent.putExtra("task", "special");
                intent.putExtra("humanCrednum", chooseValue);

                intent.putExtra("certificateTypeStr", idNumber == null ? "" : idNumber);
                intent.putExtra("orderTackTicketPhone", idPhome == null ? "" : idPhome);
                intent.putExtra("idName", idName);
                startActivity(intent);
                finish();
            }
        });


        startIDCardReader();

        openIDReader();

    }

    private void startIDCardReader() {
        // Define output log level
        LogHelper.setLevel(Log.VERBOSE);
        // Start fingerprint sensor
        Map idrparams = new HashMap();


        idrparams.put(ParameterHelper.PARAM_KEY_VID, VID);
        idrparams.put(ParameterHelper.PARAM_KEY_PID, PID);
        idCardReader = IDCardReaderFactory.createIDCardReader(this, TransportType.USB, idrparams);


    }


    void openIDReader() {
        try {
            if (bopen) return;
            idCardReader.open(0);
            bopen = true;
            textView.setText("连接设备成功");
        } catch (IDCardReaderException e) {
            textView.setText("连接设备成功");
            LogHelper.d("连接设备失败, 错误码：" + e.getErrorCode() + "\n错误信息：" + e.getMessage() + "\n 内部错误码=" + e.getInternalErrorCode());
        }
    }

    public void Authenticate() {
        try {
            idCardReader.findCard(0);
            idCardReader.selectCard(0);
        } catch (IDCardReaderException e) {
            e.printStackTrace();
        }
    }

    void readIDCard() {
        try {

            if (!bopen) {
//                textView.setText("请先连接设备");
            }
            Authenticate();
            int ret = idCardReader.readCardEx(0, 1);
            if (1 == ret) {
                IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
//                textView.setText("timeSet:" + (nTickRead - nTickStart) + "姓名：" + idCardInfo.getName() + "，民族：" + idCardInfo.getNation() + "，住址：" + idCardInfo.getAddress() + ",身份证号：" + idCardInfo.getId());
                if (idCardInfo != null) {

                    idName = idCardInfo.getName();
                    idNumber = idCardInfo.getId();
                    Log.d("shoot", "" + idNumber);
                }
//                if (idCardInfo.getPhotolength() > 0) {
//                    byte[] buf = new byte[WLTService.imgLength];
//                    nTickStart = System.currentTimeMillis();
//                    if (1 == WLTService.wlt2Bmp(idCardInfo.getPhoto(), buf)) {
//                        System.out.println("timeSet decode photo, use time:" + (System.currentTimeMillis() - nTickStart));
//                        bitmap_idPhoto = IDPhotoHelper.Bgr2Bitmap(buf);
//                        imageView.setImageBitmap(bitmap_idPhoto);
//                    }
//                }
            } else if (2 == ret) {
                IDPRPCardInfo idprpCardInfo = idCardReader.getLastPRPIDCardInfo();
//                textView.setText("timeSet:" + (nTickRead - nTickStart) + "英文名：" + idprpCardInfo.getEnName() + "，中文名：" + idprpCardInfo.getCnName() +
//                        "，国家：" + idprpCardInfo.getCountry() + ",证件号：" + idprpCardInfo.getId());
                if (idprpCardInfo != null) {

                    idName = idprpCardInfo.getEnName();
                    idNumber = idprpCardInfo.getId();
                }
//                if (idprpCardInfo.getPhotolength() > 0) {
//                    byte[] buf = new byte[WLTService.imgLength];
//                    nTickStart = System.currentTimeMillis();
//                    if (1 == WLTService.wlt2Bmp(idprpCardInfo.getPhoto(), buf)) {
//                        System.out.println("timeSet decode photo, use time:" + (System.currentTimeMillis() - nTickStart));
//                        bitmap_idPhoto = IDPhotoHelper.Bgr2Bitmap(buf);
////                        imageView.setImageBitmap(bitmap_idPhoto);
//                    }
//                }
            }

//            //保存读取的照片
//            if (bitmap_idPhoto != null) {
//
//                MyBitmapUtils.saveBitmap(bitmap_idPhoto, idPhotoPath.getAbsoluteFile());
//            }

            if (writebankcard_mobileedit != null && idNumber != null) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        writebankcard_mobileedit.setText(idNumber);
                    }
                });
            }
//            idNumber=null;

        } catch (IDCardReaderException e) {
            textView.setText("读卡失败");
            LogHelper.d("读卡失败, 错误码：" + e.getErrorCode() + "\n错误信息：" + e.getMessage() + "\n 内部错误码=" + e.getInternalErrorCode());
        }
    }

    Runnable work_readIDCard = new Runnable() {
        @Override
        public void run() {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    readIDCard();

                }
            }).start();
            handler_work.postDelayed(work_readIDCard, 2000);

        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        handler_work.postDelayed(work_readIDCard, 2000);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (writebankcard_mobileedit != null) {
            writebankcard_mobileedit.clearFocus();
        }
        if (writebankcard_Phone != null) {
            writebankcard_Phone.clearFocus();
        }
        if (handler_work != null) {
            handler_work.removeCallbacks(work_readIDCard);
        }

    }

    @Override
    protected void onRestart() {
        super.onRestart();
//        openIDReader();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Destroy fingerprint sensor when it's not used
        IDCardReaderFactory.destroy(idCardReader);
    }


    private void setChose(boolean value) {
        isChose = value;
    }

    private boolean getChose() {
        return isChose;
    }


    @Override
    public void onClick(View v) {
        Log.d("getid", "" + v.getId());
        Log.d("value", "" + chooseValue);
        switch (v.getId()) {
            case R.id.sa_btn1:
                chooseValue = "伤残证";
                setBtn(btn1);

                break;

            case R.id.sa_btn2:
                chooseValue = "军人证";
                setBtn(btn2);

                break;

            case R.id.sa_btn3:
                chooseValue = "导游证";
                setBtn(btn3);

                break;
            case R.id.sa_btn4:
                chooseValue = "记者证";
                setBtn(btn4);

                break;
            case R.id.sa_btn5:
                chooseValue = "残疾证";
                setBtn(btn5);

                break;
            case R.id.sa_btn6:
                chooseValue = "摄影证";
                setBtn(btn6);

                break;
            case R.id.sa_btn7:
                chooseValue = "老年证";
                setBtn(btn7);

                break;
            case R.id.sa_btn8:
                chooseValue = "大学生";
                setBtn(btn8);
                break;
            case R.id.sa_btn9:
                chooseValue = "医务人员";
                setBtn(btn9);
                break;

            case R.id.sa_btn10:
                chooseValue = "其他";
                setBtn(btn10);
                break;


        }
    }

    public void setBtn(Button btn) {

        if (buttonArray[0] == null) {
            buttonArray[0] = btn;

            buttonArray[0].setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_rbtn_true));
        } else {
            buttonArray[1] = btn;

            if (buttonArray[0].getId() != buttonArray[1].getId()) {
                buttonArray[0].setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_rbtn_false));
//                buttonArray[0].setBackgroundDrawable(new ColorDrawable(0xaa000000));

                buttonArray[1].setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_rbtn_true));
                buttonArray[0] = buttonArray[1];
                setChose(true);
            } else {

                if (getChose()) {
                    setChose(false);
//                    buttonArray[0].setBackgroundDrawable(new ColorDrawable(0xaa000000));
                    buttonArray[1].setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_rbtn_false));
                    //取消选择自身时，设置value为0.
                    chooseValue = "0";
                    Log.d("value", "" + chooseValue);
                } else {
                    setChose(true);
                    buttonArray[1].setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_rbtn_true));
                }
            }
        }
    }




    /*
    *
    *
    hasScanGun（）
    dispatchKeyEvent（）
    onKeyDown（）
    都是为了防止edittext获取焦点输入，二维码被读取,做的处理，不要删除
    *
    * */

    /**
     * 扫码枪是输入设备，检测是否有外接输入设备.(这样判断其实并不严格)
     *
     * @return
     */
    private boolean hasScanGun() {
        Configuration cfg = getResources().getConfiguration();
        return cfg.keyboard != Configuration.KEYBOARD_NOKEYS;
    }

//

    /**
     * Activity截获按键事件.发给 BarcodeScannerResolver
     * dispatchKeyEvent() 和 onKeyDown() 方法均可
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
//        Log.i(TAG, "dispatchKeyEvent");

        if (writebankcard_mobileedit != null) {
            writebankcard_mobileedit.setText("");
            writebankcard_mobileedit.clearFocus();
        }

        if (writebankcard_Phone != null) {
            writebankcard_Phone.setText("");
            writebankcard_Phone.clearFocus();
        }

        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (writebankcard_mobileedit != null) {
            writebankcard_mobileedit.setText("");
            writebankcard_mobileedit.clearFocus();
        }

        if (writebankcard_Phone != null) {
            writebankcard_Phone.setText("");
            writebankcard_Phone.clearFocus();
        }

        return super.onKeyDown(keyCode, event);
    }
}
